package cn.edu.zut.salarymanagesystem.activities;

import static cn.edu.zut.salarymanagesystem.utils.APKVersionInfoUtils.compareVersion;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.bean.pojo.Android;
import cn.edu.zut.salarymanagesystem.bean.vo.LoginResult;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.APKVersionInfoUtils;
import cn.edu.zut.salarymanagesystem.utils.DownloadTask;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private static final int LOGIN_JUMP = 1;
    private static final int LOGON_ALREADY = 2;
    private static final int SHOW_PROGRESS = 3;
    private static final int REQUEST_INSTALL_PERMISSION = 4;
    private DownloadTask task;

    private Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case LOGIN_JUMP:
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
                break;
            case LOGON_ALREADY:
                startActivity(new Intent(MainActivity.this, FragmentActivity.class));
                finish();
                break;
        }
        return true;
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 检查更新 0表示地址，1表示介绍
        String[] result = Objects.requireNonNull(getUpgradeInfo());
        //说明无需更新或者获取过程出错
        if (result[0] != null) {
            showUpdateDialog(result[0], result[1]);
        } else {
            new CheckLoginThread().start();
        }
    }


    private String[] getUpgradeInfo() {
        Request request = new Request.Builder().url(Storage.url + "/android/latest").build();
        FutureTask<Android> task = new FutureTask(() -> {
            String str = Browser.getClient().newCall(request).execute().body().string();
            return JSON.parseObject(str, Android.class);
        });
        new Thread(task).start();
        while (!task.isDone()) {
        }
        try {
            Android android = task.get();
            String[] ret = new String[2];
            ret[0] = compareVersion(APKVersionInfoUtils.getVersionName(this), android.getVersion()) ? android.getFileName() : null;
            ret[1] = android.getDescribe();
            return ret;
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }


    private void showUpdateDialog(String url, String describe) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本升级")
                .setIcon(R.mipmap.ic_launcher)
                .setMessage("发现高版本！请及时更新！下面是新特性：\n\n" + describe)
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    DownloadTask downloadTask = new DownloadTask(url, this);
                    this.task = downloadTask;
                    downloadTask.execute();
                    Toast.makeText(this, "请按照提示升级完程序或重新进入！", Toast.LENGTH_LONG).show();
                }).setCancelable(false)
                .setNegativeButton("取消", (dialog, which) -> new CheckLoginThread().start());
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    class CheckLoginThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                if (!checkLogon()) {
                    handler.sendEmptyMessage(LOGIN_JUMP);
                } else {
                    handler.sendEmptyMessage(LOGON_ALREADY);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        private boolean checkLogon() {
            SharedPreferences preferences = getSharedPreferences("COOKIE", MODE_PRIVATE);
            if (!preferences.contains("cookies")) {
                return false;
            } else {
                OkHttpClient client = Browser.getClient();
                Request request = new Request.Builder().url(Storage.url + "/login/isLogon").build();
                try {
                    Response execute = client.newCall(request).execute();
                    if (!execute.isSuccessful()) {
                        throw new IOException("Unexpected code " + execute);
                    }
                    String result = Objects.requireNonNull(execute.body()).string();
                    if ("NO".equals(result)) {
                        Log.i("d8g", "已过期");
                        return false;
                    } else {
                        Log.i("d8g", "已登录");
                        String currentUser = preferences.getString("currentUser", null);
                        Log.i("d8g", "checkLogon:currentUser: " + currentUser);
                        LoginResult user = JSON.parseObject(currentUser, LoginResult.class);
                        Storage.currentUser = user;
                        return user != null;
                    }
                } catch (IOException e) {
                    Log.e("d8g", "网络连接失败！" + e.getMessage());
                    e.printStackTrace();
                    return false;
                }
            }
        }
    }

    private void checkInstallPermission() {
        // 检查安装应用权限状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                // 弹出系统对话框，询问用户是否允许安装应用权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_INSTALL_PERMISSION);
            } else {
                // 已经有安装应用权限，可以直接安装应用
                task.openAPK();
            }
        } else {
            // 安装应用权限不需要申请，可以直接安装应用
            task.openAPK();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INSTALL_PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    // 用户授权，继续安装应用
                    task.openAPK();
                } else {
                    // 用户未授权，提示用户未允许安装应用权限
                    Toast.makeText(this, "未允许安装应用权限", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
